# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging
from piHAlibs import (my_fctname,coroutine,db2dict,tstampdev,unitid)
from .x10libs import *
from .parsers import DETDECODERS

logger = logging.getLogger()


@my_fctname
@coroutine
def detdecoder(targets,rejected=None,newids=None,rawevt=None):
    """
    Decoders for X10 RF Secured detectors and remotes / RFXCom and CM15 controllers
    """
    condition = " WHERE typeunit = 'detector'"
    ids = db2dict('UNITIDS',condition)
    rows = DETDECODERS
    while True:
        msgs = (yield)
       	logger.debug("Msgs received %s",repr(msgs))
        namedev, protocol, data, p, model, hdlen, revt = msgs
        if (model,protocol) not in rows : continue
        row = rows[(model,protocol)]
        logger.debug("Row associated to detector : %s",repr(row))
        if row[0] != '':
            try:
                if not eval(row[0]):
       	            if rejected: rejected.send(['FAIL_CHK1'] + data)
       	            continue
       	    except Exception as e:
                logger.error("Exception / Error %s",repr(e))
       	        continue
        if row[1] != '':
            try:
                if not eval(row[1]):
       	            if rejected: rejected.send(['FAIL_CHK2'] + data)
       	            continue
       	    except Exception as e:
                logger.error("Exception / Error %s",repr(e))
       	        continue
        try:
            huf = eval(row[2])
        except Exception as e:
       	    logger.error("Exception / Error %s",repr(e))
       	    continue
        if not huf:
       	    if rejected: rejected.send(['FAIL_DECODE'] + data)
       	    continue
        hu, f = huf
        decevt = [protocol,hu,f]
        event = tstampdev(namedev) + ['detector'] + decevt
        for target in targets:
            logger.debug("Function detdecoder for %s",repr(event))
            target.send(event)
        #Device Unit / addr
        if (protocol, hu) not in ids:
            logger.debug("New detector Id %s", hu)
            if newids:
                unitid([protocol,model,'remote',hu])
                ids = unitid([protocol,model,'detector',hu])
        if rawevt: rawevt.send([namedev,revt] + decevt)
